package com.siqi.hr.system.organization.controller;

import com.siqi.hr.common.Constants;
import com.siqi.hr.common.utils.TableConstant;
import com.siqi.hr.system.common.service.CommonOperationService;
import com.siqi.hr.system.common.sql.STable;
import com.siqi.hr.system.custom.entity.EntityRecord;
import com.siqi.hr.system.custom.service.FieldEmployeeService;
import com.siqi.hr.system.organization.entity.Dept;
import com.siqi.hr.system.organization.entity.EmpReDept;
import com.siqi.hr.system.organization.entity.Employee;
import com.siqi.hr.system.organization.service.DeptService;
import com.siqi.hr.system.organization.service.EmployeeService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 部门信息维护控制器
 * @author     xiaoxm
 * Created by xiaoxm on 2016/7/24.
 */
@Controller
@RequestMapping("Dept")
public class DeptController {

    @Autowired
    private DeptService deptService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private FieldEmployeeService fieldEmployeeService;
    @Autowired
    private CommonOperationService commonOperationService;

    /**
     * 初始化部门列表页面
     * @author    xiaogq
     * @return
     */
    @RequestMapping(value = "initDept", method = RequestMethod.GET)
    public ModelAndView initDept(HttpServletRequest request) throws Exception{
        ModelAndView mav = new ModelAndView();
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        //获取有效的所有组织(部门)数据
        JSONArray dataArray = deptService.queryDeptTree(TableConstant.DEPT_TNAME,TableConstant.Z_EMP_DEPT_TNAME,TableConstant.EMPLOYEE_TNAME,null,true);
        //获取员工头部
        Map<String,Object> columnMap = fieldEmployeeService.getEntityColumns(emp,TableConstant.EMPLOYEE_TCODE,false,true);
        mav.addObject("deptDatas",dataArray);
        //是否可以添加、编辑、删除组织架构节点(true:是，false:否)
        mav.addObject("editNode", true);
        mav.addObject("columns",columnMap.get("columns"));
        mav.addObject("fields", columnMap.get("fields"));
        mav.addObject("entity", new EntityRecord(TableConstant.EMPLOYEE_TCODE,"员工档案"));
        mav.setViewName("system/organization/dept/dept_list");
        return mav;
    }

    /**
     * 初始化部门(组织)添加页面方法
     * @param   dept     部门节点id
     * @return
     */
    @RequestMapping(value = "initAddDept", method = RequestMethod.GET)
    public ModelAndView initAddDept(HttpServletRequest request, Dept dept) throws Exception{
        ModelAndView mav = new ModelAndView();
        EntityRecord entity = new EntityRecord(TableConstant.DEPT_TCODE,"部门");
        //获取部门数据
        List<Long> deptIdList = new ArrayList<Long>();
        Long pId = dept.getParent() == null ? 0 : dept.getParent().getId();
        deptIdList.add(pId);
        //获取有效的所有组织(部门)数据
        JSONArray dataArray = deptService.queryDeptTree(TableConstant.DEPT_TNAME);
        mav.addObject("entity",entity);
        mav.addObject("dept",dept);
        mav.addObject("deptDatas",dataArray);
        mav.setViewName("system/organization/dept/dept_add");
        return mav;
    }

    /**
     * 添加保存部门(组织)方法
     * @author       xiaogq
     * @Return ModelAndView
     */
    @RequestMapping(value="saveAddDept", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveAddDept(HttpServletRequest request,Dept dept){
        //得到部门(组织)等级编码
        String deptRank = request.getParameter("deptRank") == null ? "" : request.getParameter("deptRank");
        JSONObject balkJson  = null;
        try {
            balkJson = deptService.saveAddDeptDatas(TableConstant.DEPT_TNAME,dept,deptRank);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return balkJson;
    }

    /**
     * 初始化部门(组织)编辑页面方法
     * @author  xiaogq
     * @param   deptId     部门节点id
     * @return
     */
    @RequestMapping(value = "initEditDept")
    public ModelAndView initEditDept(HttpServletRequest request, String deptId) throws Exception{
        ModelAndView mav = new ModelAndView();
        JSONArray empArray = employeeService.getAllEmpName(TableConstant.EMPLOYEE_TNAME);
        //根据id获取该记录id
        Dept dept = deptService.getById(TableConstant.DEPT_TNAME,deptId);
        List<String> managerIds = new ArrayList<String>();
        if(null != dept.getManagerIdList()){
            managerIds = dept.getManagerIdList();
        }
        JSONArray empSelArray = new JSONArray();
        for(int i = 0; i < empArray.size(); i++){
            JSONObject obj = empArray.getJSONObject(i);
            String empId = obj.get("id") == null ? "" : obj.get("id").toString();
            if (managerIds.contains(empId)){
                empSelArray.add(obj);
            }
        }
        mav.addObject("dept",dept);
        mav.addObject("managEmpIds", StringUtils.join(managerIds,","));
        mav.addObject("empAllList",empArray);
        mav.addObject("empSelList",empSelArray);
        mav.setViewName("system/organization/dept/dept_edit");
        return mav;
    }

    /**
     * 编辑保存员工档案方法
     * @author       xiaogq
     * @param        dept                   组织对象信息
     * @Return ModelAndView
     */
    @RequestMapping(value="saveEditDept", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveEditDept(HttpServletRequest request,Dept dept) throws Exception{
        String tableName = STable.TABLE_HEAD+TableConstant.DEPT_TCODE,zEmpDeptTableName = TableConstant.Z_EMP_DEPT_TNAME;
        JSONObject balkJson = new JSONObject();
        if(dept.getId().toString().equals(Constants.ROOTDEPTID)){
            balkJson.put("flag","不允许编辑根部门!");
        }else{
            balkJson  = deptService.saveEditDeptDatas(tableName,dept);
            //检查新主管是否在当前部门下，不在则新增主管所在部门
            deptService.updateMangerDept(dept.getManagerIdList(),dept.getId(),zEmpDeptTableName);
        }
        return balkJson;
    }

    /**
     * 删除部门数据
     * @param  pId    父级部门id
     * @param  id     部门id
     * @throws Exception
     */
    @RequestMapping(value = "delDept", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject delDept(HttpServletRequest request,String pId,String id) throws Exception{
        JSONObject obj = deptService.deleteDept(TableConstant.DEPT_TNAME, pId,id);
        return obj;
    }

    /**
     * 部门(组织)节点移动方法
     * @author                xiaogq
     * @param  ids           移动部门id
     * @param  pId           移动目标部门id
     * @param  orderIds    排序id
     * @throws Exception
     */
    @RequestMapping(value = "moveDept", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject moveDept(HttpServletRequest request,String ids,String pId,String orderIds) throws Exception{
        String pdeptRank = request.getParameter("pdeptRank");
        String oriDeptRank = request.getParameter("oriDeptRank");
        String deptTableName = TableConstant.DEPT_TNAME,zEmpDepTableName = TableConstant.Z_EMP_DEPT_TNAME, empTableName = TableConstant.EMPLOYEE_TNAME;
        JSONObject obj = deptService.moveDept(deptTableName,ids,pId,pdeptRank, oriDeptRank);
        //更新排序字段
        deptService.updateDeptOrders(deptTableName, orderIds);
        boolean flag = obj.getBoolean("flag");
        if(flag){
            JSONArray dataArray = deptService.queryDeptTree(deptTableName,zEmpDepTableName,empTableName,null,true);
            obj.put("data", dataArray);
        }
        return obj;
    }

    /**
     * 获取用户相关部门列表数据
     * @author   xioagq
     * @param    empReDept   员工相关部门对象
     * @return
     */
    @RequestMapping(value = "queryEmpRelateDeptAll")
    @ResponseBody
    public Map<String,Object> queryEmpRelateDeptAll(HttpServletRequest request,EmpReDept empReDept){
        empReDept.setDepTableName(TableConstant.DEPT_TNAME);
        empReDept.setzEmpDepTableName(TableConstant.Z_EMP_DEPT_TNAME);
        empReDept.setLimit(5);
        return deptService.queryEmpRelateDeptAll(empReDept);
    }

    /**
     * 添加员工与部门关系记录
     * @author   xioagq
     * @param    empId        员工id
     * @return
     */
    @RequestMapping(value = "addEmpRelateDept")
    @ResponseBody
    public JSONObject addEmpRelateDept(HttpServletRequest request,String empId){
        //获取选中相关实体(部门)记录id
        String relatedIds = request.getParameter("deptIds");
        JSONObject obj = commonOperationService.addEntityRelation(TableConstant.Z_EMP_DEPT_TNAME,empId,relatedIds);
        return obj;
    }

    /**
     * 根据id删除员工部门关系记录
     * @author   xioagq
     * @param    rId        员工与部门相关关系表id
     * @return
     */
    @RequestMapping(value = "delEmpRelateDept")
    @ResponseBody
    public JSONObject delEmpRelateDept(HttpServletRequest request,String rId){
        JSONObject obj = deptService.delEmpRelateDept(rId);
        return obj;
    }

}
